<template>
  <div style="margin-bottom: 10px">
    <span style="font-size: 25px; font-weight: bold; justify-content: center">系统账户管理</span>
  </div>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入用户名进行查询" style="width: 200px" v-model="data.name"></el-input>
      <el-button type="primary"  style="margin-left: 10px" @click="load">查询</el-button>
      <el-button type="warning"  style="margin-left: 10px" @click="reset">重置</el-button>
      <el-button type="success"  style="margin-left: 50px" @click="handleAdd">新增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div class="table">
        <el-table :data="data.tableData" stripe max-height="450px">
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="name" label="名称" width="170"></el-table-column>
          <el-table-column label="头像">
            <template #default="scope">
              <el-image :src="scope.row.avatar" style="width: 40px; height: 40px; border-radius: 50%"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="角色" prop="role">
            <template #default="scope">

              <span v-if="scope.row.role === 'SELLER'">员工</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200px">
            <template #default="scope">
              <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" plain @click="handleDelete(scope.row.userId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              style="margin-top: 5px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="data.pageNum"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close title="信息" width="40%">
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px" ref="formRef" :rules="formRules">
        <el-form-item label="头像" prop="avatar">
          <el-upload :action="uploadUrl" :on-success="handleImgSuccess" list-type="picture">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="data.form.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="data.form.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="data.form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色" prop="name">
          <el-select v-model="data.form.role" placeholder="请选择用户角色">
            <el-option
                v-for="option in data.moneyOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false" type="danger">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, onMounted,ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { hideLoading, showLoading } from "@/utils/LoadingUtil";
import {addApi, deleteApi, selectApi, updateApi} from "@/utils/API/manager/UserManager";

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'

const data = reactive({
  form: {},
  tableData: [],       // 表格数据
  pageNum: 1,          // 当前页码
  pageSize: 10,        // 每页显示数量
  total: 0,            // 总记录数
  title: null,         // 搜索条件
  formVisible: false, // 详情弹框显示状态
  name: null,
  moneyOptions: [
    { value: 'SELLER', label: '员工' },

  ]
})
const formRef = ref(null)
// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码不能少于6位',
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '员工姓名不能为空', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '角色不能为空', trigger: 'change' }
  ]
};
// 加载问答数据
const load = () => {
  const params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    name: data.name,
    role:'SELLER'
  };
  showLoading();
  selectApi(params).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list;
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg);
    }
    hideLoading();
  });
}
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.avatar = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 添加页面
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑页面
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 新增保存
const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      addApi(data.form).then(res => {
        if (res.code === '200') {
          load()
          ElMessage.success('操作成功')
          data.formVisible = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }else {
      ElMessage.error('请填写完整')
    }
  })

}

// 编辑保存
const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      updateApi(data.form).then(res => {
        if (res.code === '200') {
          load()
          ElMessage.success('操作成功')
          data.formVisible = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }else {
      ElMessage.error('请填写完整')
    }
  })
}

// 弹窗保存
const save = () => {
  // data.form有id就是更新，没有就是新增
  data.form.userId ? update() : add()
}

// 页面加载时自动调用数据加载
onMounted(() => {
  load();
})

// 重置筛选条件
const reset = () => {
  data.name = null;
  load();
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum;
  load();
}

// 处理页面大小变化
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize;
  load();
}

// 删除单条数据
const handleDelete = (id) => {
  ElMessageBox.confirm('您确定要删除此用户吗？', '确认删除', {type: 'warning'}).then(() => {
    deleteApi(id).then(res => {
      if (res.code === '200') {
        load();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

</script>

<style scoped>
@import '@/assets/css/tabelContent.css';
</style>
